package com.ssmfuse.MyFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class filter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //Filter过滤器的doFilter()方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hreq = (HttpServletRequest)request;
        HttpServletResponse hres = (HttpServletResponse)response;
        HttpSession session = hreq.getSession();
        //hreq.getContextPath()得到：/项目名
        String path1 = hreq.getContextPath() + "/User.jsp";
        String path2 = hreq.getContextPath() + "/xue/api/login";

        if(session != null && session.getAttribute("loginMessage") != null){
            //session中存在用户信息时，说明已成功登陆过，过滤器放行
            chain.doFilter(request, response);
        }else if(path1.equals(hreq.getRequestURI()) || path2.equals(hreq.getRequestURI())){
            //访问地址合法时，过滤器放行
            chain.doFilter(request, response);
        }else{
            //否则就拦截，跳转至登录页面
            System.out.println(session);
            System.out.println(path1);
            System.out.println(hreq.getContextPath() );
            System.out.println(hreq.getRequestURI());
            System.out.println(session.getAttribute("loginMessage"));
            System.out.println("请求不合法，Filter已拦截请求...");
            hres.sendRedirect(hreq.getContextPath() + "/User.jsp");
        }
    }

    @Override
    public void destroy() {

    }


}
